/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.goods.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.goods.entity.BizGoodsImp;
import vip.xiaonuo.biz.modular.goods.entity.BizGoodsImpItem;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsImpMapper;
import vip.xiaonuo.biz.modular.goods.param.GoodsImpQryDto;
import vip.xiaonuo.biz.modular.goods.result.GoodsImpPageResult;
import vip.xiaonuo.biz.modular.goods.service.BizGoodsImpItemService;
import vip.xiaonuo.biz.modular.goods.service.BizGoodsImpService;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 物品导入Service接口实现类
 *
 * @author levin
 * @date 2023/11/06 10:37
 **/
@Service
@Transactional
public class BizGoodsImpServiceImpl extends ServiceImpl<BizGoodsImpMapper, BizGoodsImp> implements BizGoodsImpService {

    @Resource
    private BizGoodsImpItemService bizGoodsImpItemService;


    @Override
    public Page<GoodsImpPageResult> getPageList(GoodsImpQryDto dto) {
        if (!StpUtil.hasRoleOr("superAdmin", "sysAdmin")) {
            SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
            dto.setUserId(saBaseLoginUser.getId());
        }
        return this.baseMapper.getPageList(CommonPageRequest.defaultPageForDto(dto), dto);
    }

    @Override
    public int impGoods(MultipartFile file) {
        int result = 0;
        try {
            ExcelReader reader = reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> dataList = reader.read();
            if (dataList.size() < 2) {
                throw new CommonException("导入文件无数据，请添加数据");
            }
            //记录批次
            BizGoodsImp goodsImp = this.addImp(0);
            List<BizGoodsImpItem> itemList = new ArrayList<>();
            for (int i = 1; i < dataList.size(); i++) {
                List<Object> data = dataList.get(i);
                BizGoodsImpItem item = new BizGoodsImpItem();
                item.setImpId(goodsImp.getId());
                item.setGoodsType(0);
                item.setGoodsCode(getObjValue(data, 0));
                item.setGoodsName(getObjValue(data, 1));
                item.setRfidNum(getObjValue(data, 2));
                item.setBarcodeFlag(getObjValue(data, 4));
                item.setQrcodeFlag(getObjValue(data, 3));
                item.setAssetCode(getObjValue(data, 5));
                item.setGoodsModel(getObjValue(data, 6));
                item.setGoodsMfr(getObjValue(data, 7));
                item.setOrgName(getObjValue(data, 8));
                item.setClassName(getObjValue(data, 9));
                item.setBioCabinet(getObjValue(data, 10));
                item.setBioCabinetDoor(getObjValue(data, 11));
                item.setAdminNames(getObjValue(data, 12));
                item.setGoodsLabels(getObjValue(data, 13));
                item.setMaxLimitLeave(getObjValue(data, 15));
                item.setImpendPrompt(getObjValue(data, 16));
                item.setAlertInterval(getObjValue(data, 17));
                item.setAlertMaxNum(getObjValue(data, 18));
                item.setSsbrFlag(getObjValue(data, 14));
                item.setGoodsDes(getObjValue(data, 19));
                item.setAttention(getObjValue(data, 20));
                item.setRemarks(getObjValue(data, 21));

                itemList.add(item);
            }
            if (!CollectionUtils.isEmpty(itemList)) {
                result = itemList.size();
                bizGoodsImpItemService.saveBatch(itemList);
            }
            //开始解析
            bizGoodsImpItemService.handleImpData(goodsImp.getId());
        } catch (IOException e) {
            throw new CommonException("导入文件解析失败");
        }
        return result;
    }

    @Override
    public int impReagent(MultipartFile file) {
        int result = 0;
        try {
            ExcelReader reader = reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> dataList = reader.read();
            if (dataList.size() < 2) {
                throw new CommonException("导入文件无数据，请添加数据");
            }
            //记录批次
            BizGoodsImp goodsImp = this.addImp(1);
            List<BizGoodsImpItem> itemList = new ArrayList<>();
            for (int i = 1; i < dataList.size(); i++) {
                List<Object> data = dataList.get(i);
                BizGoodsImpItem item = new BizGoodsImpItem();
                item.setImpId(goodsImp.getId());
                item.setGoodsType(1);
                item.setGoodsName(getObjValue(data, 0));
                item.setRfidNum(getObjValue(data, 1));
                item.setBarcodeFlag(getObjValue(data, 3));
                item.setQrcodeFlag(getObjValue(data, 2));
                item.setBioCabinet(getObjValue(data, 7));
                item.setBioCabinetDoor(getObjValue(data, 8));
                item.setMaxLimitLeave(getObjValue(data, 12));
                item.setImpendPrompt(getObjValue(data, 13));
                item.setAlertInterval(getObjValue(data, 14));
                item.setAlertMaxNum(getObjValue(data, 15));
                item.setSsbrFlag(getObjValue(data, 11));
                item.setRemarks(getObjValue(data, 19));
                item.setReagentInitNetAmount(getObjValue(data, 4));
                item.setReagentUnit(getObjValue(data, 5));
                item.setReagentValidityPeriod(getObjValue(data, 6));
                item.setReagentWeighNeedFlag(getObjValue(data, 9));
                item.setReagentMaxErrorValue(getObjValue(data, 10));
                item.setReagentBuyerName(getObjValue(data, 16));
                item.setReagentSupplier(getObjValue(data, 17));
                item.setReagentPurchaseVoucher(getObjValue(data, 18));

                itemList.add(item);
            }
            if (!CollectionUtils.isEmpty(itemList)) {
                result = itemList.size();
                bizGoodsImpItemService.saveBatch(itemList);
            }
            //开始解析
            bizGoodsImpItemService.handleImpData(goodsImp.getId());
        } catch (IOException e) {
            throw new CommonException("导入文件解析失败");
        }
        return result;
    }

    /**
     * 插入导入批次
     *
     * @param goodsType
     * @return
     */
    private BizGoodsImp addImp(int goodsType) {
        BizGoodsImp result = new BizGoodsImp();
        //获取最大数量
        int count = this.baseMapper.countForGoodsType(DateUtil.today(), goodsType);
        //补全0
        result.setGoodsType(goodsType);
        result.setImpBat(DateUtil.today().replaceAll("-", "") + String.format("%04d", count + 1));
        this.baseMapper.insert(result);
        return result;
    }

    private String getObjValue(List<Object> data, int index) {
        String result = null;
        if (index < data.size()) {
            if (data.get(index) != null) {
                result = StringUtils.deleteWhitespace(data.get(index).toString());
            }
        }
        return result;
    }
}
